package exteditapp;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;

import exteditapp.command.ICommand;
import exteditapp.command.CommandStart;
import exteditapp.state.IState;
import exteditapp.state.StateError;
import exteditapp.state.StateIdling;
import exteditapp.state.StateIdlingLocked;
import exteditapp.state.StateIdlingUpdated;
import exteditapp.state.StateStarting;

/**
 * @todo
 * 1. two boxes - one for button mode, and another for progress mode.
 * 2. on gui mode change we interchange boxes, not components.
 */


/**
 * Main program applet (Plone edition) implemented to run in browser environment
 * 
 * 
 * @author Arturas Smorgun, arturas@smorgun.lt
 * @version 2009.04.17
 */
public class ModuleAppletDefault extends IModuleApplet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 3135162766751150375L;
	
	protected static ModuleAppletDefault _instance = null;
	
	/**
	 * Default constructor
	 */
	public ModuleAppletDefault(){
		super();
		_instance = this;
	}

	/**
	 * 
	 */
	public static ModuleAppletDefault getInstance(){
		if(_instance == null)
			_instance = new ModuleAppletDefault();
		return _instance;
	}
	
	/**
	 * Notifies listeners about changed state
	 */
	public void notifyListeners() {
		IState state = null;
		if(getWorkingFile() != null)
			state = getWorkingFile().getCurrentState();
		Iterator<IListener> listenerIterator = listeners.iterator();
		while(listenerIterator.hasNext()){
			listenerIterator.next().update(state);
		}
	}

	/**
	 * Paint method.
	 */
	public void paint() {
		//TODO implement paint
		
	}

	/**
	 * What happens on startup?
	 */
	public void init(){
		
		//Execute starting operation
		ICommand startCommand = new CommandStart();
		startCommand.execute();
		
		//set file state to FileStateStart
		workingFile = new FileDefault(null);
		workingFile.setModule(this);
		
		//construct controller and empty iterator
		IController controller = new ControllerDefault(this);
		iterator = new AppletIterator(controller);
		
		this.setVisible(true);
		
		//construct view
		ViewDefault view = new ViewDefault();
		view.setController(controller);
		view.init();
		
		//register view to module
		if(registerListener(view))
			view.setSubject(this);
		
		//change state of listeners
		notifyListeners();
		
		//check if gained priveleges
		if(!this.isSafetToUseClipboard()){
			StateError nState = new StateError(iterator, workingFile);
			nState.setup("YOU SHOULD TRUST OUR CERTIFICATE");
			workingFile.setCurrentState(nState);
		}
		else{
			
			//current state - start of execution
			StateStarting newState = new StateStarting(iterator, workingFile);
			workingFile.setCurrentState(newState);
			
			//start program iterator
			new Thread(iterator).start();
		}
	}
	
	public void start(){}
	
	/**
	 * What happens on shutdown? (this one doesn't works if browser was killed instead of proper exit
	 */
	public void destroy() {
		//TODO implement shutdown
		
		this.invoker.interrupExecutions();
		
		if(this.workingFile != null){
			IState cState = workingFile.getCurrentState();
			if(!(cState instanceof StateIdling || cState instanceof StateIdlingLocked || cState instanceof StateIdlingUpdated)){
				/**
				 * Do unlock.
				 */
				
				try{
					URL myCheckUrl = new URL(workingFile.getDownloadURL()+workingFile.getModule().URL_DO_UNLOCK);
					HttpURLConnection connection = (HttpURLConnection) myCheckUrl.openConnection();
					connection.setConnectTimeout(3000);
					connection.setReadTimeout(3000);
					String lockPath = workingFile.getModule().getSettings().getParameter("lockPath");
					String lockToken = workingFile.getModule().getSettings().getParameter("lockToken");
					connection.setRequestProperty("If", "<"+lockPath+"> (<"+lockToken+">)");
					BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
					String locked = br.readLine();
					connection.disconnect();
					//executed if file locking is failed
					if(locked.compareTo("1") != 0){
						System.out.println("Don't work: |"+locked+"|");
					}
					System.out.println("UNLOCKED");
				}
				catch(Exception e){}
			}
			else
				System.out.println("NOT UNLOCKED");
		}
		else
			System.out.println("NOT UNLOCKED");
	}
	
	public void stop(){}

}
